<!--
  @author:  long
  @date:    2023/4/6
  @file:    xx
  @require:
-->
<template>
  <div class="uploadIndicator">
    <el-steps :active="stepActive" style="margin: 0 20px">
      <el-step title="上传文件" />
      <el-step title="数据校验" />
      <el-step title="导入成功" />
    </el-steps>
    <div v-show="stepActive == 1" class="mt-10" v-loading="upload.loading">
      <el-upload
        ref="uploadRef"
        :action="upload.url"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :file-list="fileList"
        :headers="upload.headers"
        :limit="1"
        :on-error="handleFileError"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".xlsx, .xls"
        :on-change="handleFileUploadChange"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span style="font-size: 14px"
              >请根据模板填写表格内容。<el-button
                type="text"
                @click.stop="handleDownload"
                >下载模板</el-button
              ></span
            >
          </div>
        </template>
      </el-upload>
    </div>
    <el-row v-show="stepActive == 2" class="mt-5">
      <el-col :span="12">
        <el-descriptions title="校验结果" :column="1" border align-center>
          <el-descriptions-item label="正确数据（条）：">{{
            correctNum
          }}</el-descriptions-item>
          <el-descriptions-item label="错误数据（条）：">{{
            errorNum
          }}</el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>
    <el-row v-show="stepActive == 3" class="mt-5">
      <el-col :span="24">
        <el-descriptions title="上传结果" :column="1" align-center>
          <el-descriptions-item label="结果">{{
            uploadResultMsg
          }}</el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>
    <div class="flex items-center justify-end mt-5">
      <el-button v-show="stepActive != 1" type="danger" @click="domErrorData"
        >导出错误数据</el-button
      >
      <el-button
        v-show="stepActive == 2"
        type="primary"
        :disabled="correctNum == 0"
        @click="submitFileForm"
        >确认上传</el-button
      >
      <el-button @click="uploadDialogClose">关 闭</el-button>
    </div>
    <el-dialog v-model:visible="errorDialogVisible" title="提示" width="30%">
      <div
        style="
          white-space: pre-wrap;
          line-height: 30px;
          max-height: 50vh;
          overflow: auto;
        "
        v-html="errorDialogContent"
      />
    </el-dialog>
  </div>
</template>

<script setup name="UploadIndicator">
import { getToken } from '@/utils/auth'
import { getCurrentInstance } from 'vue'
import {
  importBizofficeconfData,
  importHyBizofficeconfData,
  outPutBizofficeconfFail
} from '@/api/officeManage/indicator'
import { download } from '@/utils/request'

const { proxy } = getCurrentInstance()

const data = reactive({
  stepActive: 1,
  correctNum: 0,
  errorNum: 0,
  upload: {
    loading: false,
    // 是否显示弹出层（开票导入）
    open: false,
    // 弹出层标题（开票导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer_' + getToken() },
    // 上传的地址
    // url: process.env.VUE_APP_BASE_API + '/biz/ywkpxx/importData'
    url: ''
  },
  fileList: [],
  errorDialogVisible: false,
  errorDialogContent: '',
  uploadResultMsg: ''
})
const {
  stepActive,
  upload,
  correctNum,
  errorNum,
  fileList,
  errorDialogVisible,
  errorDialogContent,
  uploadResultMsg
} = toRefs(data)

/**
 * 下载模板
 */
const handleDownload = () => {
  // let url =
  //   import.meta.env.VITE_APP_API +
  //   '/template/绩效考核管理/绩效考核指标导入模板.xlsx'
  let url =
    'http://192.168.1.110:9000/template/绩效考核管理/绩效考核指标导入模板.xlsx'
  window.open(url)
}

/** 提交上传文件 */
const submitFileForm = () => {
  proxy.$refs['uploadRef'].submit()
  importHyBizofficeconfData().then(res => {
    stepActive.value = 3
    uploadResultMsg.value = res.msg
  })
}

// 导出上传的错误数据
const domErrorData = () => {
  proxy.download(
    '/office/bizofficeconf/outPutFailExcel',
    {},
    '考核指标错误数据.xlsx'
  )
  // outPutBizofficeconfFail().then(res => {
  //   console.info('res', res)
  //   //投标项目立项模板导出
  //   // proxy.downLoadByUrl(
  //   //   '/ord/order/ordbiddinginformation/resultsExport?projectId=',
  //   //   {},
  //   //   `投标项目立项模板_${new Date().getTime()}.xlsx`
  //   // )
  // })
}
const emits = defineEmits(['dialogClose'])
// 上传弹窗关闭时回调
const uploadDialogClose = () => {
  if (stepActive.value == 3) {
    fileList.value = []
  }
  stepActive.value = 1
  correctNum.value = 0
  errorNum.value = 0
  uploadResultMsg.value = ''
  emits('dialogClose')
}

/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.value.isUploading = true
}
/** 上传文件失败处理*/
const handleFileError = () => {
  fileList.value = []
  upload.value.open = false
  upload.value.isUploading = false
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file) => {
  if (response.code === 500) {
    errorDialogVisible.value = true
    errorDialogContent.value = response.msg
  }
  fileList.value = []
  upload.value.open = false
  upload.value.isUploading = false
  // 添加文件时回调
}
/** 文件上传前处理  校验*/
const handleFileUploadChange = file => {
  console.info('file', file)
  const formData = new FormData()
  formData.append('file', file.raw)
  console.info('formData', formData)
  upload.value.loading = true
  importBizofficeconfData(formData)
    .then(res => {
      console.info('res', res)
      correctNum.value = res.data
      errorNum.value = res.data2
      if (stepActive.value == 1) {
        stepActive.value = 2
      }
    })
    .finally(() => {
      upload.value.loading = false
    })
}
</script>

<style scoped lang="scss">
.uploadIndicator {
  padding: 20px;
}
</style>
